import { createStore } from 'vuex'
import { getLyric, phoneLogin, userDetail } from '@/api'

export default createStore({
  state: {
    playlist: [{
      al: {},
      name: '',
      id: ''
    }],
    playCurrentIndex: 0,
    lyric: '',
    currentTime: 0,
    intervalId: 0,
    user: {
      isLogin: localStorage.isLogin || false,
      account: {},
      userDetail: {}
    }
  },
  getters: {
    lyricList (state) {
      let arr = state.lyric.split(/\n/igs).map((item, i) => {
        item = item.replace(/\s+/g, '');
        let min = parseInt(item.slice(1, 3));
        let sec = parseInt(item.slice(4, 6));
        let mill = parseInt(item.slice(7, 10));
        return {
          min, sec, mill,
          lyric: item.slice(10, item.length).replace(']', ''),
          content: item,
          time: mill + sec * 1000 + min * 60 * 1000
        }
      })
      arr.forEach((item, i) => {
        if (i == 0) {
          item.pre = 0;
        } else {
          item.pre = arr[i - 1].time;
        }
      })
      return arr;
    }
  },
  mutations: {
    setPlaylist (state, data) {
      state.playlist = data;
    },
    pushPlaylist (state, data) {
      state.playlist.push(data);
    },
    setPlayIndex (state, data) {
      state.playCurrentIndex = data;
    },
    setLyric (state, data) {
      state.lyric = data;
    },
    setCurrentTime (state, data) {
      state.currentTime = data;
    },
    setUser (state, data) {
      state.user = data;
    }
  },
  actions: {
    async reqLyric ({ commit }, payload) {
      let result = await getLyric(payload.id);
      console.log(result);
      commit('setLyric', result.data.lrc.lyric);
    },
    async phoneLogin ({ commit, state }, payload) {
      let result = await phoneLogin(payload.phone, payload.password);
      console.log(result, '333');
      if (result.data.code == 200) {
        state.user.isLogin = true;
        state.user.account = result.data.account;
        let userData = await userDetail(result.data.account.id);
        console.log(userData, '123123');
        state.user.userDetail = userData.data;
        localStorage.userData = JSON.stringify(state.user);
        commit('setUser', state.user);
      }
      console.log(result);
      return result;
    }
  },
  modules: {
  }
})
